//
//  AUSwapContentView.swift
//  AwesomeUHomeModule_Example
//
//  Created by Miss_Special on 2018/4/16.
//  Copyright © 2018 CocoaPods. All rights reserved.
//

import UIKit

import SnapKit

// MARK:- <协议>
public protocol AUSwapContentViewDelegate: class {
    func swapContentView(
        _ swapContentView: AUSwapContentView,
        progress: CGFloat,
        sourceIndex: Int,
        targetIdex: Int)
}

private let AUSwapContentViewCellIdentifier = "AUSwapContentViewCellIdentifier"

public class AUSwapContentView: UIView {
    
    /// 当前显示的内容
    fileprivate var currentViewControllers: [UIViewController]
    /// 当前滚动到的indexPath
    fileprivate var currentIndexPath: IndexPath = IndexPath(row: 0, section: 0)
    
    // MARK:- <Porperty - Normal>
    fileprivate var childViewControllers: [UIViewController]
    // 外面的XQHomeViewController强引用了当前的view, 而当前的view也强引用着XQHomeViewController, 造成了循环引用, 所以将强引用改成弱引用, 改为弱引用之后, 变为可选类型
    fileprivate weak var parrentViewController: UIViewController?
    fileprivate var startX: CGFloat = 0
    public weak var delegate: AUSwapContentViewDelegate?
    fileprivate var isForbidScrollDelegate: Bool = false
    
    // MARK:- <Property - Lazy>
    // 这个懒加载的闭包中用到了self, 会造成循环引用, 为了解决循环引用, 需要用到[weak self], 使用了[weak self]之后, self变为可选类型
    fileprivate lazy var collectionView: UICollectionView = {[weak self] in
        
        // 创建layout
        let layout = UICollectionViewFlowLayout()
        layout.itemSize = (self?.bounds.size)!
        layout.minimumLineSpacing = 0
        layout.minimumInteritemSpacing = 0
        layout.scrollDirection = UICollectionViewScrollDirection.horizontal
        
        // 创建collectionView
        let collectionView = UICollectionView(frame: CGRect.zero, collectionViewLayout: layout)
        collectionView.backgroundColor = UIColor.white
        collectionView.bounces = false
        collectionView.showsHorizontalScrollIndicator = false
        /** 控制器中的ScrollView需要关闭这个属性, 才不会遮挡系统的点击顶部滚动到最上边的事件 **/
        collectionView.scrollsToTop = false
        collectionView.isPagingEnabled = true
        collectionView.register(UICollectionViewCell.self, forCellWithReuseIdentifier: AUSwapContentViewCellIdentifier)
        collectionView.dataSource = self
        collectionView.delegate = self
        
        return collectionView
        }()
    
    // MARK:- <自定义构造函数>
    public init(frame: CGRect, childViewControllers: [UIViewController], parrentViewController: UIViewController?) {
        // 保存属性
        self.childViewControllers = childViewControllers
        self.parrentViewController = parrentViewController
        
        self.currentViewControllers = childViewControllers
        
        super.init(frame: frame)
        
        // 设置UI界面
        setupUI()
    }
    required public init?(coder aDecoder: NSCoder) {
        fatalError("init(coder:) has not been implemented")
    }
}

// MARK:- <设置UI>
extension AUSwapContentView {
    
    /// 设置UI界面
    fileprivate func setupUI() {
        
        // 将控制器添加到父控制器中
        for childViewController in childViewControllers {
            parrentViewController?.addChildViewController(childViewController)
        }
        
        addSubview(collectionView)
        collectionView.snp.makeConstraints { (make) in
            make.edges.equalToSuperview()
        }
        collectionView.frame = bounds
    }
}

// MARK:- <UICollectionViewDataSource>
extension AUSwapContentView: UICollectionViewDataSource {
    
    public func collectionView(_ collectionView: UICollectionView, numberOfItemsInSection section: Int) -> Int {
        return currentViewControllers.count
    }
    
    public func collectionView(_ collectionView: UICollectionView, cellForItemAt indexPath: IndexPath) -> UICollectionViewCell {
        
        let cell = collectionView.dequeueReusableCell(withReuseIdentifier: AUSwapContentViewCellIdentifier, for: indexPath)
        
        for subView in cell.contentView.subviews {
            subView.removeFromSuperview()
        }
        
        let childViewController = currentViewControllers[(indexPath as NSIndexPath).item]
        childViewController.view.frame = cell.contentView.bounds
        cell.contentView.addSubview(childViewController.view)
        
        return cell
    }
}

// MARK:- <UICollectionViewDelegate>
extension AUSwapContentView: UICollectionViewDelegate {
    
    public func scrollViewWillBeginDragging(_ scrollView: UIScrollView) {
        
        isForbidScrollDelegate = false
        
        // 获取滚动的起始位置
        startX = scrollView.contentOffset.x
    }
    
    public func scrollViewDidScroll(_ scrollView: UIScrollView) {
        
        if isForbidScrollDelegate { return }
        
        var progress: CGFloat
        var sourceIndex: Int
        var targetIndex: Int
        
        let currentOffsetX: CGFloat = scrollView.contentOffset.x
        let scrollViewWidth: CGFloat = scrollView.frame.size.width
        
        if currentOffsetX > startX { // 向左滑动
            // 1. progress
            progress = currentOffsetX / scrollViewWidth - floor(currentOffsetX / scrollViewWidth)
            
            // 2.sourceIndex
            sourceIndex = Int(currentOffsetX / scrollViewWidth)
            
            // 3.targetIndex
            targetIndex = sourceIndex + 1
            if targetIndex >= childViewControllers.count - 1 {
                targetIndex = childViewControllers.count - 1
            }
            
            // 4.完全划过去
            if currentOffsetX - startX == scrollViewWidth {
                progress = 1
                targetIndex = sourceIndex
            }
        } else { // 向右滑动
            // 1.progress
            progress = 1 - (currentOffsetX / scrollViewWidth - floor(currentOffsetX / scrollViewWidth))
            
            // 2.targetIndex
            targetIndex = Int(currentOffsetX / scrollViewWidth)
            
            // 3.targetIndex
            sourceIndex = targetIndex + 1
            if sourceIndex >= childViewControllers.count - 1 {
                sourceIndex = childViewControllers.count - 1
            }
        }
        
        delegate?.swapContentView(self, progress: progress, sourceIndex: sourceIndex, targetIdex: targetIndex)
    }
    
    public func scrollViewDidEndScrollingAnimation(_ scrollView: UIScrollView) {
        
        if currentViewControllers.count != childViewControllers.count {
            // 假象_还原
            currentViewControllers = childViewControllers
            collectionView.reloadData()
            collectionView.scrollToItem(at: currentIndexPath, at: .centeredHorizontally, animated: false)
        }
    }
}

// MARK:- <公共接口>
extension AUSwapContentView {
    
    /// collectionView滚动
    public func setCurrentPage(_ toIndex: Int) {
        // 点击标题滚动时, 禁止手动拖拽
        isForbidScrollDelegate = true
        // 记录滚动到的indexPath
        currentIndexPath = IndexPath(row: toIndex, section: 0)
        
        // new
        let currentIndex = Int(collectionView.contentOffset.x / collectionView.frame.size.width)
        
        // 假象_滚动
        currentViewControllers = [childViewControllers[currentIndex], childViewControllers[toIndex]]
        collectionView.reloadData()
        collectionView.scrollToItem(at: IndexPath(row: 0, section: 0), at: .centeredHorizontally, animated: false)
        let indexPath = IndexPath(row: 1, section: 0)
        self.collectionView.scrollToItem(at: indexPath, at: UICollectionViewScrollPosition.centeredHorizontally, animated: true)
    }
}
